package com.pig4cloud.pig.juhe.api.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.pig.juhe.api.vo.ChannelConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author yuwenfeng
 * @description: python工具类
 * @date 2021/9/9 11:43
 */
@Slf4j
public class PythonUtil {
	public static void main(String[] args) throws Exception {
		/*try {
			//读取apk包信息，步骤一
            String apkpath = "D:\\nginxWork\\nginx-1.21.1\\html\\upload\\packageIn\\test.apk";//路径
            String pythonpath1 = "D:\\javaworkspace\\pythonWork\\batch_package\\auto\\JavaCallLoadApkReturnInfo.py";
			String[] strs = new String[]{"python", pythonpath1, apkpath};
			Process process = Runtime.getRuntime().exec(strs);
			BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
			String line;
			while ((line = in.readLine()) != null) {
				System.out.println(line);
				if(line.indexOf("packageInfo")>0){
					JSONObject json=JSON.parseObject(line);
					JSONObject info=json.getJSONObject("packageInfo");
					System.out.println(info.toJSONString());
				}
			}
			in.close();
			// java代码中的 process.waitFor() 返回值（和我们通常意义上见到的0与1定义正好相反）
			// 返回值为0 - 表示调用python脚本成功；
			// 返回值为1 - 表示调用python脚本失败。
			int re = process.waitFor();
			System.out.println("调用 python 脚本是否成功：" + re);
			System.exit(0);
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}*/
		/*String apkpath = "D:\\nginxWork\\nginx-1.21.1\\html\\upload\\packageIn\\4d9933b1d8dd41cb837e4c16f5d8a029.apk";//路径
		String pythonpath1 = "D:\\javaworkspace\\pythonWork\\batch_package\\auto\\JavaCallLoadApkReturnInfo.py";
		System.out.println(pythonExec(pythonpath1,apkpath,"packageInfo"));*/

		/*List<ChannelConfig> configList = getPythonConfig(Constant.CHANNEL_CONFIG_PATH);
		System.out.println("configList：" + JSONObject.toJSONString(configList));*/
		/*String str = readTxtFile("D:\\javaworkspace\\pythonWork\\batch_package\\auto\\config\\3367.txt");
		JSONObject jsonData=JSON.parseObject(str);
		System.out.println(jsonData.getString("gameName"));
		for (Map.Entry entry : jsonData.entrySet()) {
			System.out.println(entry.getKey());
		}*/
	}

	/**
	 * @description: 执行python脚本
	 * @author yuwenfeng
	 * @date 2021/9/14 16:59
	 */
	public static String pythonExec(String pythonPath, String param, String key) throws Exception {
		String result = "";
		String[] strs = new String[]{"python", pythonPath, param};
		Process process = Runtime.getRuntime().exec(strs);
		BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
		String line;
		while ((line = in.readLine()) != null) {
			log.info("python返回值：{}",result);
			if (line.indexOf(key) > 0) {
				result = JSON.parseObject(line).getString(key);
				System.out.println("python转换值："+result);
				log.info("python转换值：{}",result);
			}
		}
		in.close();
		// java代码中的 process.waitFor() 返回值（和我们通常意义上见到的0与1定义正好相反）
		// 返回值为0 - 表示调用python脚本成功；
		// 返回值为1 - 表示调用python脚本失败。
		int re = process.waitFor();
		System.out.println("调用 python 脚本是否成功：" + re);
		log.info("调用 python 脚本是否成功：{}",re);
		if (StringUtils.isNotBlank(result) && 0 == re) {
			return result;
		}
		return null;
	}

	/**
	 * @description: 读取打包工具的渠道配置
	 * @author yuwenfeng
	 * @date 2021/9/15 17:14
	 */
	public static List<ChannelConfig> getPythonConfig(String path) throws DocumentException {
		SAXReader reader = new SAXReader();
		//2.读取xml文件，获得Document对象
		Document doc = reader.read(new File(path));
		//3.获取根元素
		Element root = doc.getRootElement();
		//4.获取根元素下的所有子元素（通过迭代器）
		Iterator<Element> it = root.elementIterator();
		List<ChannelConfig> list = new ArrayList<ChannelConfig>();
		ChannelConfig info = null;
		while (it.hasNext()) {
			Element e = it.next();
			Element channel = e.element("channel");
			Attribute name = e.attribute("name");
			Attribute cname = e.attribute("cname");
			Attribute channelid = e.attribute("channelid");
			Attribute sdkversion = e.attribute("sdkversion");
			Attribute updateversion = e.attribute("updateversion");
			Attribute updatetime = e.attribute("updatetime");
			info = new ChannelConfig();
			info.setName(name.getStringValue());
			info.setCname(cname.getStringValue());
			info.setChannelid(channelid.getStringValue());
			info.setSdkversion(sdkversion.getStringValue());
			info.setUpdateversion(updateversion.getStringValue());
			info.setUpdatetime(updatetime.getStringValue());
			list.add(info);
		}
		return list;
	}

	/**
	 * @description: 读取txt文件内容
	 * @author yuwenfeng
	 * @date 2021/9/15 17:54
	 */
	public static String readTxtFile(String filePath) throws IOException {
		String encoding = "UTF-8";
		StringBuilder resultStr = new StringBuilder();
		File file = new File(filePath);
		if (file.isFile() && file.exists()) { //判断文件是否存在
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				//System.out.println(lineTxt);
				resultStr.append(lineTxt);
			}
			read.close();
		} else {
			System.out.println("找不到指定的文件");
		}
		return resultStr.toString();
	}

	/**
	 * 获取扩展名
	 */
	public static String getExtension(MultipartFile file) {
		String originalFilename = file.getOriginalFilename();
		return originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
	}
}
